package com.along.htybrowser;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.along.htybrowser.adapter.FavoriteAdapter;
import com.along.htybrowser.databinding.ActivityFavoriteBinding;
import com.along.htybrowser.greendao.dao.FavoriteTabDao;
import com.along.htybrowser.greendao.tab.FavoriteTab;
import com.along.htybrowser.utils.AutoLog;
import com.along.htybrowser.utils.FileUtil;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class FavoriteActivity extends Activity {
    private ActivityFavoriteBinding binding;
    private InputMethodManager IMM;
    FavoriteAdapter adapter;
    private List<FavoriteTab> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityFavoriteBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        IMM = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);

        binding.imageButtonClear.setOnClickListener(new OnClickListener());
        binding.imageButtonClear.setVisibility(View.GONE);
        binding.editText.addTextChangedListener(new EditChangedListener());

        list = new ArrayList<>();
        adapter = new FavoriteAdapter(list);
        binding.rv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        binding.rv.setAdapter(adapter);
        adapter.setOnItemClickListener((view, position) -> {
            String url = list.get(position).getWebsite();

            Intent intent = new Intent(FavoriteActivity.this, MainActivity.class);
            intent.putExtra("url", url);
            setResult(RESULT_OK, intent);
            IMM.hideSoftInputFromWindow(binding.editText.getWindowToken(), 0);
            finish();
        });
        binding.rv.setOnCreateContextMenuListener((menu, view, menuInfo) -> {
            AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
            String title = ((TextView) info.targetView.findViewById(R.id.title)).getText().toString();
            menu.setHeaderTitle(title);
            menu.add(0, 0, 0, "复制链接");
            menu.add(0, 1, 1, "删除");
            menu.add(0, 2, 2, "修改");
            menu.add(0, 3, 3, "分享");
        });
        binding.rv.setOnTouchListener((v, event) -> {
            IMM.hideSoftInputFromWindow(binding.editText.getWindowToken(), 0);
            return false;
        });

        search(binding.editText.getText().toString());
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        String[] sm = {"导出HTML", "导出CSV"};
        for (int i = 0; i < sm.length; i++) {
            menu.add(0, i, i, sm[i]);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case 0:
                StringBuilder sb = new StringBuilder("<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\"/>\n<title>收藏夹</title>\n<style>a { text-decoration:none; }\ntable { table-layout:fixed; width:100%; border-collapse:collapse; }\nth, td { border:1px solid black; padding:5px; overflow:hidden; text-overflow: ellipsis; }\n</style>\n</head>\n<body>\n<h2 align=center>收藏夹" + list.size() + "</h2>\n<table>\n<tr><th>标题</th><th>网址</th></tr>\n");
                for (int i = 0; i < list.size(); i++) {
                    sb.append("<tr><td>").append(list.get(i).getTitle()).append("</td><td><a href=\"").append(list.get(i).getWebsite()).append("\" target=\"_blank\">").append(list.get(i).getWebsite()).append("</a></td></tr>\n");
                }
                sb.append("</table>\n</body>\n</html>");
                String fileName = FileUtil.writeFile("webfav.htm", sb.toString());
                if (fileName != null) {
                    Toast.makeText(FavoriteActivity.this, "写文件 " + FileUtil.dir + File.separator + fileName + " 成功", Toast.LENGTH_SHORT).show();
                }
                break;
            case 1:
                sb = new StringBuilder();
                for (int i = 0; i < list.size(); i++) {
                    sb.append(list.get(i).getTitle().replace(",", "，")).append(",").append(list.get(i).getWebsite()).append("\n");
                }
                String fileName2 = FileUtil.writeFile("webfav.csv", sb.toString());
                if (fileName2 != null) {
                    Toast.makeText(FavoriteActivity.this, "写文件 " + FileUtil.dir + File.separator + fileName2 + " 成功", Toast.LENGTH_SHORT).show();
                }
                break;
            case android.R.id.home:
                IMM.hideSoftInputFromWindow(binding.editText.getWindowToken(), 0);
                finish();
                break;
        }
        return true;
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
        int position = menuInfo.position;
        switch (item.getItemId()) {
            case 0://复制链接
                ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                String url = ((TextView) menuInfo.targetView.findViewById(R.id.website)).getText().toString();
                cm.setPrimaryClip(ClipData.newPlainText("link", url));
                Toast.makeText(getApplicationContext(), "链接已复制", Toast.LENGTH_SHORT).show();
                break;
            case 1://删除
                App.getInstance().getDaoSession().getFavoriteTabDao().delete(list.get(position));
                list.remove(position);
                adapter.notifyItemChanged(position);
                break;
            case 2://修改
                final String stitle = ((TextView) menuInfo.targetView.findViewById(R.id.title)).getText().toString();
                final String surl = ((TextView) menuInfo.targetView.findViewById(R.id.website)).getText().toString();
                LinearLayout layout = new LinearLayout(FavoriteActivity.this);
                layout.setOrientation(LinearLayout.VERTICAL);
                final EditText ET_title = new EditText(FavoriteActivity.this);
                ET_title.setHint("标题");
                ET_title.setText(stitle);
                layout.addView(ET_title);
                final EditText ET_url = new EditText(FavoriteActivity.this);
                ET_title.setHint("网址");
                ET_url.setText(surl);
                layout.addView(ET_url);
                AlertDialog.Builder builder = new AlertDialog.Builder(FavoriteActivity.this);
                builder.setIcon(android.R.drawable.btn_star_big_on);
                builder.setTitle("修改收藏");
                builder.setView(layout);
                builder.setPositiveButton("确定", (dialog, which) -> {
                    String stitle1 = ET_title.getText().toString();
                    String surl1 = ET_url.getText().toString();
                    Field field = null;
                    try {
                        //通过反射获取dialog中的私有属性mShowing
                        field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                        field.setAccessible(true);//设置该属性可以访问
                    } catch (Exception ignored) {
                    }
                    if (!stitle1.equals("") && (surl1.startsWith("http") || !surl1.startsWith("file:///"))) {
                        FavoriteTab favoriteTab = list.get(position);
                        favoriteTab.setTitle(stitle1);
                        favoriteTab.setWebsite(surl1);
                        App.getInstance().getDaoSession().getFavoriteTabDao().update(favoriteTab);
                        adapter.notifyItemChanged(position);
                        IMM.hideSoftInputFromWindow(ET_title.getWindowToken(), 0);
                        try {
                            //关闭
                            field.set(dialog, true);
                            dialog.dismiss();
                        } catch (Exception ignored) {
                        }
                    } else {
                        if (stitle1.equals("")) {
                            ET_title.setError("标题不能为空！");
                        }
                        if (!surl1.startsWith("http") || !surl1.startsWith("file:///")) {
                            ET_url.setError("网址错误！");
                        }
                        try {
                            //设置dialog不可关闭
                            field.set(dialog, false);
                            dialog.dismiss();
                        } catch (Exception ignored) {
                        }
                    }
                });
                builder.setNegativeButton("取消", (dialog, which) -> {
                    IMM.hideSoftInputFromWindow(ET_title.getWindowToken(), 0);
                    Field field = null;
                    try {
                        //通过反射获取dialog中的私有属性mShowing
                        field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                        field.setAccessible(true);//设置该属性可以访问
                    } catch (Exception ignored) {
                    }
                    try {
                        field.set(dialog, true);
                        dialog.dismiss();
                    } catch (Exception ignored) {
                    }
                });
                builder.create().show();
                break;
            case 3:
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_TEXT, ((TextView) menuInfo.targetView.findViewById(R.id.title)).getText().toString() + "\n" + ((TextView) menuInfo.targetView.findViewById(R.id.website)).getText().toString());
                intent.setType("text/plain");
                startActivity(Intent.createChooser(intent, "分享"));
                break;
        }
        return true;
    }

    class OnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.imageButton_clear) {
                binding.editText.setText("");
            }
        }
    }

    void search(String s) {
        List<FavoriteTab> favoriteTabs;
        if (TextUtils.isEmpty(s)) {
            favoriteTabs = App.getInstance().getDaoSession().getFavoriteTabDao().loadAll();
        } else {
            favoriteTabs = App.getInstance().getDaoSession().getFavoriteTabDao()
                    .queryBuilder()
                    .whereOr(FavoriteTabDao.Properties.Website.like("%" + s + "%"), FavoriteTabDao.Properties.Title.like("%" + s + "%"))
                    .list();
        }
        int count = favoriteTabs.size();
        setTitle("收藏夹" + count);
        list.clear();
        list.addAll(favoriteTabs);
        adapter.notifyDataSetChanged();
    }

    class EditChangedListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().equals("")) {
                binding.imageButtonClear.setVisibility(View.GONE);
            } else {
                binding.imageButtonClear.setVisibility(View.VISIBLE);
            }
            search(s.toString());
        }
    }
}